import {$get, $post, baseForm} from '@/js/ajax'

const user = {
  state: {
    userId: localStorage.getItem('userId'),
    userInfo: null,
    menuList: []
  },

  mutations: {
    SET_USER_ID(state, id) {
      state.userId = id
      if (isEmpty(id)) {
        localStorage.removeItem('userId')
      } else {
        localStorage.setItem('userId', id)
      }

    },
    SET_USER_INFO(state, userInfo) {
      state.userInfo = userInfo
      // baseForm.userId = userInfo && userInfo.id
      baseForm.companyId = userInfo && userInfo.companyId
    },
    SET_MENU_LIST(state, menuList) {
      state.menuList = menuList
    }
  },

  actions: {
    // 登录
    async Login({commit}, data) {
      let body = await $post('admin/login', data, {showError: false})
      const id = body.obj.admin.id
      commit('SET_USER_ID', id)
    },


    async GetInfo({commit, state}) {
      // 获取用户信息
      if (!state.userId) throw new Error('no find userId')
      let body = await $get('admin/getAdminById', {id: state.userId})
      commit('SET_USER_INFO', body.obj)

      // 获取可见菜单列表
      let body2 = await $get('admin/getRoleByRoleId', {roleId: state.userId})
      const menusStr = body2.obj.muneList || ''
      commit('SET_MENU_LIST', menusStr.split(','))
    },

    // 登出
    async LogOut ({commit, state}) {
      commit('SET_USER_INFO', null)
      commit('SET_USER_ID', null)
      // const {code, obj} = await $post('/user/logout')
      // return code == 200 && obj
    },

    // 前端 登出
    FedLogOut({commit}) {
      commit('SET_USER_INFO', null)
      commit('SET_USER_ID', null)
    }
  }
}

export default user
